import VRSim.Globals as globals
from VRSim.Utils import debug,  message
from VRSim.Node.CiscoDomain import CiscoDomain
from VRSim.Node.C3600Device import C3600Device


class CiscoDomain3600(CiscoDomain):
    def __init__(self,  nodeid):
        debug("init CiscoDomain3600")
        CiscoDomain.__init__(self,  nodeid)
        self.devices = C3600Device(nodeid)
        # 3600 Specific 
        self.vcpu = "1"
        self.npetype = "3640"
        self.npetype_list = ["3620", "3640",  "3660"]
        self.midplane = None
        self.midplane_list = []
        

    #########
    # Operation
    #########
    def start(self,  vm):
        # check log directory
        # check disk image is exist?
        vminst = globals.GApp.topology.getVMAPI(self.nodeid)
        hdd = self.devices.hdd.source
        if not vminst.exists(hdd):
            msg = "HDD image(%s) does not exist" % hdd
            message(msg,  "critical")
            node = globals.GApp.topology.nodes[self.nodeid]
            cfg = Config(node.physnode,  page="HardDisk")
            cfg.show()
            cfg.exec_()
            return False
            
        # start virtual machine
        # find URL by vm
        # get XML object
        debug("called CiscoDomain3600 : start")
        domain = self.getXML()
        
        hypervisors = globals.GApp.topology.hypervisors
        for hypervisor in hypervisors:
            name = hypervisor[0]
            if name == vm:
                uri = hypervisor[2]
                temp = uri.split(":")
                self.host = str(temp[0])
                self.port = int(temp[1])
                
        commands = []
        # set working directory
        # hypervisor working_dir <dir>
        commands.append("hypervisor working_dir " + globals.working_directory + "/.dynamips/")
        # create instance
        # vm create <instance_name> <instance_id> <model>
        commands.append( "vm create " + str(self.name) + " " + str(self.instantID) + "  c3600"  )
        # ios_file : vm set_ios <instance_name> <ios_file>
        commands.append( "vm set_ios " + str(self.name) + " " + str(self.devices.hdd.source) )
        # conf_file : vm set_config <instance_name> <cfg_file>
        commands.append( "vm set_config " + str(self.name) + " " + str(self.cfg))
        # console:  vm set_con_tcp_port <instance_name> <tcp_port>
        commands.append( "vm set_con_tcp_port " + str(self.name) + " " + str(self.devices.console) )
        # c3600 set_chassis <instance_name> <chassis_name> 
        commands.append( "c3600 set_chassis " + str(self.name) + " " + str(self.npetype))
        
        # network binding create
        # nio binding
        # interface install
        count = 0
        keys = self.devices.slot.keys()
        keys.sort()
        
        
        for slotName in keys:
            slot = self.devices.slot[slotName]
            adapter = slot['adapter']
            # enable slot
            #commands.append( "c7200 pa_init_online " + str(self.name) + " " + str(count))
            # attach slot
            # check enabled
            firstInterface = slot[0]
            if firstInterface.isEnabled == False:
                continue
                 
            commands.append( "vm slot_add_binding " + str(self.name) + " " + str(count) + " 0 " + adapter[0])
            for portN in range(adapter[1]): # ports
                # make nio
                interface = slot[portN]
                if interface.isAssigned == True and interface.type == "Internal":
                    # make UDP nio
                    nio_name = str(self.name) + "_" + str(count) + "_" + str(portN)
                    self.nioList.append(nio_name)
                    commands.append("nio create_udp " + nio_name + " " + str(interface.srcPort) + " " + str(interface.dstIP) + " " + str(interface.dstPort) )
                    commands.append( "vm slot_add_nio_binding " + str(self.name) + " " + str(interface.slot) + " " + str(interface.port) + " " + nio_name)
            count = count + 1
            
        # start
        commands.append( "vm start " + str(self.name))
        
        # open telnet connection
        if not self.conn:
            self.conn = self.getSocket()
        
        try:
            for command in commands:
                debug(command)
                self.conn.send(command + "\n")
            tf = True
        except:
            tf = False
         
        if tf == True:
            msg = globals.eventMsg["start"]
            nmsg = msg % globals.GApp.topology.getNodeName(self.nodeid)
            globals.GApp.mainWindow.NodesLog.addEvent(nmsg)
            return True
        else:
            msg = globals.errorMsg["start"]
            nmsg = msg % globals.GApp.topology.getNodeName(self.nodeid)
            globals.GApp.mainWindow.NodesLog.addError(nmsg)
            return False  
